package org.apache.dubbo.samples.basic;

import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.SslConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.samples.basic.api.DemoService;
import org.apache.dubbo.samples.basic.impl.DemoServiceImpl;

import java.util.concurrent.CountDownLatch;

/**
 * @author duan
 * @version 1.0
 * @date 2023/2/24 9:24
 */
public class SslBasicProvider {


    private static String zookeeperHost = System.getProperty("zookeeper.address", "127.0.0.1");
    private static String zookeeperPort = System.getProperty("zookeeper.port", "2181");

    private static String zookeeperAddress = "zookeeper://"+ zookeeperHost +":" + zookeeperPort;

    public static void main(String[] args) throws Exception {
//        new EmbeddedZooKeeper(Integer.parseInt(zookeeperPort), false).start();
        // wait for embedded zookeeper start completely.
//        Thread.sleep(1000);

        SslConfig sslConfig = new SslConfig();
        if (args.length > 0) {
            if (args.length < 2 || args.length > 3) {
                System.out.println(
                        "USAGE: BasicProvider certChainFilePath privateKeyFilePath " +
                                "[trustCertCollectionFilePath]\n Specify 'trustCertCollectionFilePath' only if you want " +
                                "need Mutual TLS.");
                System.exit(0);
            }


            sslConfig.setServerKeyCertChainPath(args[0]);
            sslConfig.setServerPrivateKeyPath(args[1]);
            if (args.length == 3) {
                // 如果开启双向cert认证，需要配置
                sslConfig.setServerTrustCertCollectionPath(args[2]);
            }
        }

        ProtocolConfig protocolConfig = new ProtocolConfig("dubbo");
        protocolConfig.setSslEnabled(true);

        DubboBootstrap bootstrap = DubboBootstrap.getInstance();
        bootstrap.application(new ApplicationConfig("ssl-provider"))
                .registry(new RegistryConfig(zookeeperAddress))
                .protocol(protocolConfig)
                .ssl(sslConfig);

        ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
        service.setInterface(DemoService.class);
        service.setRef(new DemoServiceImpl());
        service.setVersion("1.0.0");
        service.setTimeout(20000);

        bootstrap.service(service);
        bootstrap.start();

        System.out.println("dubbo service started");
        new CountDownLatch(1).await();
    }
}
